#include <stdio.h>
#include <string.h>
#include "jpeglib.h"
#include <setjmp.h>
#include <stdlib.h>
#include <photo_manager.h>

static int jpegIsSupport(char *filename);
static int jpegGetDispData(char *filename, PT_imageInfo image);

static T_PhotoOpr jpegOpr = 
{
	.name 			= "jpg",
	.isSupport 		= jpegIsSupport,
	.getDispData 	= jpegGetDispData,
	.next			= NULL,
};

static int jpegIsSupport(char *filename)
{
	if(filename ==NULL)
	{
		fprintf(stderr, "the parama error\n");
		return 0;
	}

	if(strstr(filename, ".jpg")==NULL)
	{
		return 0;
	}
	else
		return 1;

	return 0;
}

static int jpegGetDispData(char *filename, PT_imageInfo image)
{
	struct jpeg_decompress_struct cinfo;
	struct jpeg_error_mgr jerr;
	FILE * infile;						/* source file */
	int row_stride;
	unsigned char *buffer;
	unsigned char *jpgBuffer;

	//1创建结构体
	cinfo.err = jpeg_std_error(&jerr);
	jpeg_create_decompress(&cinfo);
	
	//2初始化结构体
	if ((infile = fopen(filename, "rb")) == NULL) 
	{
		fprintf(stderr, "can't open %s\n", filename);
		return -1;
	}
	jpeg_stdio_src(&cinfo, infile);
	
	//3读取文件头信息
	jpeg_read_header(&cinfo, TRUE);
	
	//4设置放大缩小比例
//	scanf("%d/%d",&cinfo.scale_num, &cinfo.scale_denom);
	
	//5解压
	jpeg_start_decompress(&cinfo);

	image->height 	= cinfo.output_height;
	image->width 	= cinfo.output_width;
	image->iBpp 	= cinfo.output_components*8;
	image->isBMP	= 0;

	//6显示
	row_stride = cinfo.output_width * cinfo.output_components;
	buffer = malloc(row_stride);
	jpgBuffer = malloc(row_stride*(cinfo.output_height));
		
	while (cinfo.output_scanline < cinfo.output_height) 
	{
		jpeg_read_scanlines(&cinfo, &buffer, 1);
		memcpy(jpgBuffer+(row_stride*(cinfo.output_scanline-1)), buffer, row_stride);
	}
	
	image->imageDataBuff = jpgBuffer;
	
	//7完成解压
	jpeg_finish_decompress(&cinfo);
	
	//8释放资源
	jpeg_destroy_decompress(&cinfo);
	free(buffer);
	fclose(infile);

	return 0;
}

int jpegInit(void)
{
	int ret;

	ret = registerPhotoOpr(&jpegOpr);
	return ret;
}


